#include "v1model.p4"

#define BASE 10
#define PORT_THRESH ((1 << BASE) -1)
#define K 4
#define M 2 // 路径标识号占据位数
#define N 6 // 主机号字段用位数
#define MASK (0xFFFFFFFF - (bit<32>)(((1<<M)-1) << 6))

// 类型常量定义
const bit<16> TYPE_IPV4 = 0x0800;
const bit<8> TYPE_TCP =0x06;
const bit<8> TYPE_UDP =0x11;

typedef bit<9>  egressSpec_t;
typedef bit<8> route_index_t;


// 寄存器容量定义
const bit<32> NUMBER_65536 = 0xFFFF;
const bit<32> NUMBER_256 = 256;
const bit<32> NUMBER_2024 = 2024;


/*************************************************************************
*********************** H E A D E R S  ***********************************
*************************************************************************/

// 以太网报头
header ethernet_h {
    bit<48> dstAddr;
    bit<48> srcAddr;
    bit<16> etherType;
}

// IPv4报头
header ipv4_h {
    bit<4>  version;
    bit<4>  ihl;
    bit<8>  diffserv;  // 用于存储route_index
    bit<16> totalLen;
    bit<16> identification;
    bit<3>  flags;
    bit<13> fragOffset;
    bit<8>  ttl;
    bit<8>  protocol;
    bit<16> hdrChecksum;
    bit<32> srcAddr;
    bit<32> dstAddr;
}


header tcp_h {
    bit<16> srcPort;
    bit<16> dstPort;
    bit<32> seqNo;
    bit<32> ackNo;
    bit<4>  dataOffset;
    bit<3>  res;
    bit<3>  ecn;
    bit<6>  ctrl;
    bit<16> window;
    bit<16> checksum;
    bit<16> urgentPtr;
}

header udp_h {
    bit<16> src_port;  // Source port
    bit<16> dst_port;  // Destination port
    bit<16> length;    // Length of UDP packet
    bit<16> checksum;  // Checksum
}


struct metadata{
    route_index_t route_index;
    bit<16> random_value;
    bit<16> port; // TCP或者UDP的端口号
    bit<32> port_forwarded_number; // 端口已经转发的字节数量
}

struct headers {
    ethernet_h ethernet;
    ipv4_h ipv4;
    tcp_h tcp;
    udp_h udp;
}


/*************************************************************************
*********************** P A R S E R  ***********************************
*************************************************************************/

parser P4ECMPParser(packet_in packet,
                out headers hdr,
                inout metadata meta,
                inout standard_metadata_t standard_metadata) {
    
    state start {
        transition parse_packet;
    }

    state parse_packet{

        transition select(standard_metadata.ingress_port){
            default: parse_ethernet;
        }
    }

    state parse_ethernet{
        
        packet.extract(hdr.ethernet);
        transition select(hdr.ethernet.etherType){

            TYPE_IPV4: parse_ipv4;
            default: accept;
        }
    }

    state parse_ipv4{
        packet.extract(hdr.ipv4);
        transition select(hdr.ipv4.protocol){
            TYPE_TCP: parse_tcp;
            TYPE_UDP: parse_udp;
            default: accept;
        }
    }

    state parse_tcp{
        packet.extract(hdr.tcp);
        transition accept;
    }

    state parse_udp{
        packet.extract(hdr.udp);
        transition accept;
    }
}

/*************************************************************************
************   C H E C K S U M    V E R I F I C A T I O N   *************
*************************************************************************/

control P4ECMPVerifyChecksum(inout headers hdr, inout metadata meta) {
    apply { 
        
    }
}

/*************************************************************************
**************  I N G R E S S   P R O C E S S I N G   *******************
*************************************************************************/

control P4ECMPIngress(inout headers hdr,
                  inout metadata meta,
                  inout standard_metadata_t standard_metadata) {

    register<egressSpec_t>(NUMBER_256) route_index_to_port_register;

    action set_mac(bit<48> mac_dst) {
        hdr.ethernet.srcAddr = hdr.ethernet.dstAddr;
        hdr.ethernet.dstAddr = mac_dst;
    }
    
    table mac_table {
        key = { 
            standard_metadata.egress_spec: exact; 
        }
        actions = {
            set_mac;
            NoAction;
        }
        default_action = NoAction;
        size = 256;
    }

    action ipv4_forward(egressSpec_t port){
        standard_metadata.egress_spec = port;
        hdr.ipv4.ttl = hdr.ipv4.ttl - 1;
    }

    table ipv4_forward_table{
        key={
            hdr.ipv4.dstAddr:lpm;
        }
        actions={
            ipv4_forward;
            NoAction;
        }
        default_action = NoAction;
        size = 1024;
    }

    action cross_net_forward(){

        bit<32> hash_value;
        if(hdr.udp.isValid()){
            hash(hash_value,
                HashAlgorithm.crc32,
                (bit<32>)0,
                {hdr.ipv4.srcAddr,hdr.ipv4.dstAddr,hdr.udp.src_port,hdr.udp.dst_port},
                (bit<32>)0xFFFFFFFF);    
        }else if(hdr.tcp.isValid()){
            hash(hash_value,
                HashAlgorithm.crc32,
                (bit<32>)0,
                {hdr.ipv4.srcAddr,hdr.ipv4.dstAddr,hdr.tcp.srcPort,hdr.tcp.dstPort},
                (bit<32>)0xFFFFFFFF);
        }else{
            hash(hash_value,
                HashAlgorithm.crc32,
                (bit<32>)0,
                {hdr.ipv4.srcAddr,hdr.ipv4.dstAddr,hdr.ipv4.protocol},
                (bit<32>)0xFFFFFFFF);
        }
        meta.route_index = (route_index_t)(hash_value % K);
        egressSpec_t port;
        route_index_to_port_register.read(port,(bit<32>)meta.route_index);
        standard_metadata.egress_spec = port;
    }


    apply {
        if (hdr.ipv4.isValid()) {

            // 进行内网流量转发
            if(ipv4_forward_table.apply().miss){

                // 进行跨网络流量转发，确定报文输出端口
                cross_net_forward();                
            }
        }
        // 设置mac地址
        mac_table.apply();
    }
}

/*************************************************************************
****************  E G R E S S   P R O C E S S I N G   *******************
*************************************************************************/

control P4ECMPEgress(inout headers hdr,
                 inout metadata meta,
                 inout standard_metadata_t standard_metadata) {
    
    // 对端口流量进行统计
    register<bit<32>>(NUMBER_256) port_forwarded_bytes;
    register<bit<32>>(NUMBER_256) port_forwarded_packets;


    apply{
        bit<32> forwarded_bytes;
        bit<32> forwarded_packets;

        port_forwarded_bytes.read(forwarded_bytes,(bit<32>)standard_metadata.egress_port);
        port_forwarded_packets.read(forwarded_packets,(bit<32>)standard_metadata.egress_port);

        port_forwarded_bytes.write((bit<32>)standard_metadata.egress_port,(bit<32>)standard_metadata.packet_length + forwarded_bytes);
        port_forwarded_packets.write((bit<32>)standard_metadata.egress_port,forwarded_packets + 1);

        port_forwarded_bytes.read(forwarded_bytes,(bit<32>)standard_metadata.ingress_port + 128);
        port_forwarded_packets.read(forwarded_packets,(bit<32>)standard_metadata.ingress_port + 128);

        port_forwarded_bytes.write((bit<32>)standard_metadata.ingress_port + 128,(bit<32>)standard_metadata.packet_length + forwarded_bytes);
        port_forwarded_packets.write((bit<32>)standard_metadata.ingress_port + 128,forwarded_packets + 1);

    }

}

/*************************************************************************
*************   C H E C K S U M    C O M P U T A T I O N   **************
*************************************************************************/

control P4ECMPComputeChecksum(inout headers hdr, inout metadata meta) {
     apply {
        update_checksum(
            hdr.ipv4.isValid(),
            { hdr.ipv4.version,
              hdr.ipv4.ihl,
              hdr.ipv4.diffserv,
              hdr.ipv4.totalLen,
              hdr.ipv4.identification,
              hdr.ipv4.flags,
              hdr.ipv4.fragOffset,
              hdr.ipv4.ttl,
              hdr.ipv4.protocol,
              hdr.ipv4.srcAddr,
              hdr.ipv4.dstAddr },
            hdr.ipv4.hdrChecksum,
            HashAlgorithm.csum16);
    
    }
}


/*************************************************************************
***********************  D E P A R S E R  *******************************
*************************************************************************/

control P4ECMPDeparser(packet_out packet, in headers hdr) {

    apply{
        packet.emit(hdr.ethernet);
        packet.emit(hdr.ipv4);
        packet.emit(hdr.tcp);
        packet.emit(hdr.udp);
    }
}

/*************************************************************************
***********************  S W I T C H  *******************************
*************************************************************************/

V1Switch(
P4ECMPParser(),
P4ECMPVerifyChecksum(),
P4ECMPIngress(),
P4ECMPEgress(),
P4ECMPComputeChecksum(),
P4ECMPDeparser()
) main;